
from openpyxl import load_workbook as xlsxread


class ReadXLSX:
    def __init__(self, path='./vcard.xlsx'):
        self.__openfin(path)
        self.__loadbook()
        self.__loadsheet()

    def __openfin(self, path='./vcard.xlsx', mode='rb'):
        self.__fin = path
        self.__workbook = None

    def __closefin(self):
        if self.__workbook:
            self.__workbook.close()
            self.__workbook = None

    def __loadbook(self):
        self.__workbook = xlsxread(self.__fin, read_only=True)

    def __loadsheet(self):
        self.__sheetnames = self.__workbook.sheetnames
        self.__sheets = []
        for sheet in self.__workbook:
            self.__sheets.append(sheet)

    def close(self):
        self.__closefin()

    def readsheet(self, row, col, readline=False):
        sheet = self.__sheets[0]

        if row > sheet.max_row or col > sheet.max_column:
            return []

        if readline == True:
            rows = sheet[row]

            line = []
            for cell in rows:
                line.append(str('' if cell.value == None else cell.value))
            return line

        else:
            value = sheet.cell(row, col).value
            return str(value)

    def readsheetall(self, row=1):
        sheet = self.__sheets[0]
        i = 0
        for rows in sheet:
            i += 1
            if i < row:
                continue

            line = []
            for cell in rows:
                line.append(str(cell.value))
            yield line
